package com.itheima.thread;

/*
* 案例需求
生产者消费者案例中包含的类：
奶箱类(Box)：定义一个成员变量，表示第x瓶奶，提供存储牛奶和获取牛奶的操作
生产者类(Producer)：实现Runnable接口，重写run()方法，调用存储牛奶的操作
消费者类(Customer)：实现Runnable接口，重写run()方法，调用获取牛奶的操作
测试类(BoxDemo)：里面有main方法，main方法中的代码步骤如下
①创建奶箱对象，这是共享数据区域
②创建消费者创建生产者对象，把奶箱对象作为构造方法参数传递，因为在这个类中要调用存储牛奶的操作
③对象，把奶箱对象作为构造方法参数传递，因为在这个类中要调用获取牛奶的操作
④创建2个线程对象，分别把生产者对象和消费者对象作为构造方法参数传递
⑤启动线程
代码实现
* */
public class XiaoFei implements Runnable {
    private Mulk b;

    public XiaoFei(Mulk b) {
        this.b = b;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //Thread.sleep(1000);
                b.getCount();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

class Mulk {
    private int milk;
    boolean state = false;
    //boolean falg=false;

    public synchronized void getCount() throws InterruptedException {
        if (!state) {
            wait();
        }
        System.out.println("用户拿到第" + this.milk + "瓶奶");
        state = false;
        notifyAll();
    }

    public synchronized void setCount(int milk) {
        if (state) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.milk = milk;
            System.out.println("送奶工将第" + this.milk + "瓶奶放入奶箱");
            state = true;
            notifyAll();
        }
    }
}

class Reduce implements Runnable {
    private Mulk b;

    public Reduce(Mulk b) {
        this.b = b;
    }


    @Override
    public void run() {
        for (int i = 1; i <= 30; i++) {
            b.setCount(i);
        }

    }
}

class T {
    public static void main(String[] args) {
        Mulk mulk = new Mulk();
        XiaoFei xf = new XiaoFei(mulk);
        Reduce rd = new Reduce(mulk);
        Thread t1 = new Thread(xf);
        Thread t2 = new Thread(rd);
        t1.start();
        t2.start();
    }
}
